<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import {
  ElNotification,
  ElMessage,
  type FormInstance,
  type FormRules,
  type UploadProps,
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const uploadActionUrl = `${import.meta.env.VITE_API_BASE_URL}/api/files/upload`

const router = useRouter()
const userStore = useUserStore() // 使用 Pinia Store

const formRef = ref<FormInstance>()
const activeName = ref('login')

// 在表单数据中新增 avatarUrl 字段
const formModel = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  avatarUrl: '', // 用于存储上传成功后的头像URL
})

// 表单验证规则
const rules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formModel.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

// 上传前的校验函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 检查文件大小是否超过 1MB
  if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('头像文件大小不能超过 1MB!')
    return false // 阻止上传
  }
  return true // 允许上传
}

// 头像上传成功时的回调函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  // response 就是后端 /api/files/upload 接口返回的图片 URL
  formModel.avatarUrl = response
  ElNotification.success('头像上传成功！')
}

// 提交表单
const submit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (activeName.value === 'login') {
          await userStore.login(formModel.username, formModel.password)
          ElNotification.success('登录成功！')
          router.push('/home')
        } else {
          // 注册时，传递包含头像 URL 的完整表单
          await userStore.register(formModel.username, formModel.password, formModel.avatarUrl)
          ElNotification.success('注册成功，已自动为您登录！')
          router.push('/home')
        }
      } catch (err: any) {
        const errorMsg = err.response?.data?.message || '操作失败，请检查用户名或密码'
        ElNotification.error(errorMsg)
      }
    }
  })
}
</script>

<template>
  <div class="login-container">
    <el-card class="login-card">
      <el-tabs v-model="activeName" class="login-tabs">
        <el-tab-pane label="登录" name="login"></el-tab-pane>
        <el-tab-pane label="注册" name="register"></el-tab-pane>
      </el-tabs>

      <el-form ref="formRef" :model="formModel" :rules="rules" label-width="0">
        <el-form-item v-if="activeName === 'register'" prop="avatarUrl" class="avatar-form-item">
          <el-upload
            class="avatar-uploader"
            :action="uploadActionUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formModel.avatarUrl" :src="formModel.avatarUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

            <template #tip>
              <div class="el-upload__tip">请上传头像，文件大小最好不超过 1MB。</div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item prop="username">
          <el-input v-model="formModel.username" placeholder="请输入用户名" size="large" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item v-if="activeName === 'register'" prop="confirmPassword">
          <el-input
            v-model="formModel.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit" class="submit-btn" size="large">
            {{ activeName === 'login' ? '登 录' : '注 册' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}
.login-card {
  width: 400px;
}
.login-tabs {
  margin-bottom: 20px;
}
:deep(.el-tabs__nav-wrap::after) {
  height: 0;
}
.submit-btn {
  width: 100%;
}
.avatar-form-item {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  flex-direction: column;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 50%; /* 圓形 */
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px; /* 調整大小 */
  height: 120px;
  text-align: center;
}
.avatar {
  width: 120px; /* 調整大小 */
  height: 120px;
  display: block;
}
.el-upload__tip {
  text-align: center;
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

/* --- 新增：移動端適配 --- */
@media (max-width: 768px) {
  .login-card {
    width: 90%; /* 在小螢幕上，寬度變為90% */
  }
}
</style>
